package com.luo.service;

import com.luo.spring.BeanPostProcessor;
import com.luo.spring.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@Component
public class BeanPostProcessorTest implements BeanPostProcessor {
    @Override
    public Object postProcessBeanBeforeInitialization(String beanName, Object bean) {
        if (beanName.equals("user")){
            System.out.println("user这个bean被创建之前我要先打印一下");
        }
        return bean;
    }

    @Override
    public Object postProcessBeanAfterInitialization(String beanName, Object bean) {
        if (beanName.equals("orderService")){
            System.out.println("orderService这个bean被创建之后我要先打印一下");

        }
        if (beanName.equals("orderService")){
            Object proxyBean=Proxy.newProxyInstance(BeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    System.out.println("代理类被创建");
                    return method.invoke(bean,args);
                }
            });
            return proxyBean;
        }
        return bean;

    }
}
